<?php

App::uses('CrudController', 'Controller');
App::uses('TeamUser', 'Model');

class TeamUsersController extends CrudController
{
    public $_model = 'TeamUser';

    public function getResume($teamId, $lineId, $userId = null)
    {
        $this->request->allowMethod('get');
        $data = array();
        if ($this->request->is('ajax') === true) {
            $this->loadModel('UserLine');
            $this->loadModel('Categorization');
            $this->loadModel('Test');
            $userLine = $this->UserLine->getByUserAndLine($userId, $lineId);
            if (isset($userLine['UserLine']) === true) {
                $level = $userLine['UserLine']['level'];
                $this->Categorization->id = $level;
                $categorization = $this->Categorization->read();
                $test = null;
                if ($categorization['Categorization']['test_id'] !== null) {
                    $this->Test->id = $categorization['Categorization']['test_id'];
                    $test = $this->Test->read();
                }
                $categorization['Categorization']['daysCert'] = $userLine['UserLine']['days'] >= $categorization['Categorization']['lower_limit'] ? '1' : '0';
                $next = $this->Categorization->getNext($userId, $level);
                $next['daysCert'] = $userLine['UserLine']['days'] >= $next['cat.lower_limit'] ? '1' : '0';
                $data['level'] = array(
                    'certifications' => $userLine['UserLine']['certifications'],
                    'current' => $categorization['Categorization'],
                    'test' => $test['Test'],
                    'next' => $next,
                );
            }
            $data['resumen'] = $this->TeamUser->getResumeByTeamAndLineAndUser($teamId, $lineId, $userId);
        }
        $this->set(array('data' => $data, '_serialize' => 'data'));
        $this->viewClass = 'Json';
    }

    public function addUsers($teamId)
    {
        $this->request->allowMethod('get');
        $success = new stdClass();
        if ($this->request->is('ajax') === true) {
            $this->loadModel('User');
            $this->loadModel('Team');
            $this->loadModel('UserLine');
            $this->Team->id = $teamId;
            $resTeam = $this->Team->read();
            $team = $resTeam['Team'];
            $strUsers = $this->request->query['u'];
            $users = explode(' ', $strUsers);
            $errors = array();
            foreach ($users as $nomina) {
                if (trim($nomina) != '') {
                    $user = $this->User->getAssociatedByNomina(trim($nomina));
                    if (isset($user['User']) === true) {
                        $resUserLine = $this->UserLine->getByUserAndLine($user['User']['id'], $team['line_id']);
                        if ($resUserLine) {
                            $teamUserData = array(
                                'user_id' => $user['User']['id'],
                                'team_id' => $teamId,
                                'type' => TeamUser::TYPE_NORMAL,
                                'status' => TeamUser::STATUS_ENABLED,
                            );
                            $this->TeamUser->save($teamUserData);
                            $this->TeamUser->clear();
                        } else {
                            $error = new stdClass();
                            $error->rc = '01';
                            $error->nomina = $nomina;
                            array_push($errors, $error);
                        }
                    } else {
                        $error = new stdClass();
                        $error->rc = '01';
                        $error->nomina = $nomina;
                        array_push($errors, $error);
                    }
                }
            }
            $success->result = true;
            $success->errors = $errors;
        }
        $this->set(array('success' => $success, '_serialize' => 'success'));
        $this->viewClass = 'Json';
    }

    public function deleteUsers($teamId)
    {
        $this->request->allowMethod('get');
        $success = new stdClass();
        if ($this->request->is('ajax') === true) {
            $this->loadModel('User');
            $this->loadModel('Team');
            $this->loadModel('UserLine');
            $this->Team->id = $teamId;
            $strUsers = $this->request->query['u'];
            $users = explode(' ', $strUsers);
            $errors = array();
            foreach ($users as $nomina) {
                if (trim($nomina) != '') {
                    $user = $this->User->getByNomina($nomina);
                    if (isset($user['User'])) {
                        $this->TeamUser->deleteMember($teamId, $user['User']['id']);
                    } else {
                        $error = new stdClass();
                        $error->rc = '04';
                        $error->nomina = $nomina;
                        array_push($errors, $error);
                    }
                }
            }
            $success->result = true;
            $success->errors = $errors;
        }
        $this->set(array('success' => $success, '_serialize' => 'success'));
        $this->viewClass = 'Json';
    }

    public function getUsersByTeam($teamId)
    {
        $this->layout = null;

        if ($this->request->is('ajax') === true) {
            $this->loadModel('Team');
            $this->Team->id = $teamId;
            $team = $this->Team->read();
            $resp = new stdClass();
            $resp->name = $team['Team']['name'];
            $resp->line = $team['Team']['real_line_id'];
            $this->loadModel('TeamUser');
            $resp->users = $this->TeamUser->getUsersByTeam($teamId);
            $this->set('resp', $resp);
        }
    }

    public function getActiveTeamUsers($teamId)
    {
        $this->request->allowMethod('get');
        $resp = new stdClass();
        if ($this->request->is('ajax') === true) {
            $this->loadModel('TeamUser');
            $resp->users = $this->TeamUser->getActiveTeamUsers($teamId);
        }
        $this->set(array('resp' => $resp, '_serialize' => 'resp'));
        $this->viewClass = 'Json';
    }

    public function addTeamUser()
    {
        $this->request->allowMethod('get');
        $resp = new stdClass();
        $this->loadModel('UserLine');
        $userId = $this->request->query('user_id');
        $lineId = $this->request->query('line_id');
        $resUser = $this->UserLine->getByUserAndLine($userId, $lineId);
        $resp->rc = "00";
        if ($resUser) {
            $data = array(
                "id" => $this->request->query['id'],
                "team_id" => $this->request->query['team_id'],
                "user_id" => $userId,
                "type" => $this->request->query['type'],
                "full_name" => $this->request->query['full_name'],
                "curp" => $this->request->query['curp'],
                "nomina" => $this->request->query['nomina'],
                "admission_date" => $this->request->query['admission_date']);
            $this->TeamUser->save($data);
        } else {
            $resp->rc = '01'; //No existe usuario para la línea
        }
        $this->set(array('resp' => $resp, '_serialize' => 'resp'));
        $this->viewClass = 'Json';
    }

    public function toggleUserLeader($teamUserId)
    {
        $m = $this->_model;
        $tu = $this->$m->findById($teamUserId);
        $tu['TeamUser']['leader'] = $tu['TeamUser']['leader'] == '1' ? 0 : 1;
        $resp = $this->$m->save($tu);
        $this->set(array('resp' => isset($resp[$m]), '_serialize' => 'resp'));
        $this->viewClass = 'Json';
    }

    protected function getRecords($param)
    {
        $m = $this->_model;
        $records = $this->$m->getTeam($param);
        return $records;
    }

    protected function c($model)
    {
        return array(
            'type' => $model->type,
            'user_id' => $model->user_id,
            'team_id' => $model->team_id,
        );
    }

    protected function u($model)
    {
        return array(
            'type' => $model->type,
            'user_id' => $model->user_id,
        );
    }
}
